package org.jiangpz.excel.merge.process;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.jiangpz.excel.merge.entity.RowEntity;

public class ReadFile {
	
	int countAll = 0;
	
	/**
	 * 读取Excel2003
	 * 
	 * @param filePath
	 * @return
	 */
	public List<RowEntity> readFromXLS2003(String filePath) {
		File excelFile = null;// Excel文件对象
		InputStream is = null;// 输入流对象
		Double cellVal = null;// 单元格，最终按字符串处理
		char A = 'A';
		char R = 'R';
		List<RowEntity> rowEntityList = new ArrayList<RowEntity>();// 返回封装数据的List
		RowEntity rowEntity = null;// 每一个初始对象
		try {
			excelFile = new File(filePath);
			is = new FileInputStream(excelFile);// 获取文件输入流
			HSSFWorkbook workbook2003 = new HSSFWorkbook(is);// 创建Excel2003文件对象
			HSSFSheet sheet = workbook2003.getSheetAt(0);// 取出第一个工作表，索引是0
			// 开始循环遍历行，表头不处理，从4开始
			for (int i = 4; i <= sheet.getLastRowNum(); i++) {
				if(i == 30) break;
				countAll++;
				rowEntity = new RowEntity();// 实例化Row对象
				HSSFRow row = sheet.getRow(i);// 获取行对象
				if (row == null) {// 如果为空，不处理
					continue;
				}
				// 循环遍历单元格
				for (int j = 2; j < row.getLastCellNum(); j++) {
					if(j > ((int)R -(int)A)){
						continue;
					}
					HSSFCell cell = row.getCell(j);// 获取单元格对象
					if (cell == null) {// 单元格为空设置cellStr为空串
						cellVal = (double) 0;
					} else {// 其余按照字符串处理
						cellVal = cell.getNumericCellValue();
					}
					
					rowEntity = Util.setValue(rowEntity, j, cellVal);
				}
				rowEntityList.add(rowEntity);// 数据装入List
				workbook2003.close();
				System.out.println(rowEntity);
				System.out.println(countAll);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {// 关闭文件流
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return rowEntityList;
	}


}
